<template>
  <div class="shopping-cart">
    <el-card v-for="product in cartItems" :key="product.id">
      <div>
        <h3>{{ product.name }}</h3>
        <p>价格：{{ product.price }}￥</p>
        <p>数量: {{ product.quantity }}</p>
        <el-checkbox v-model="selectedItems[product.id]" @change="onCheckboxChange(product.id, $event)" />
        <el-button type="danger" @click="removeOne(product.id)">删除一个</el-button>
        <el-button type="danger" @click="removeAll(product.id)">删除全部</el-button>
      </div>
    </el-card>
    <!-- 底部栏显示选中商品的总价和下单按钮 -->
    <div v-if="hasSelectedItems" class="checkout-bar">
      <p>已选商品数量：{{ selectedItemCount }}</p>
      <p>已选商品总价：{{ selectedItemTotal }}￥</p>
      <el-button type="primary" @click="placeOrder">下单</el-button>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';

export default {
  name: 'ShoppingCart',
  computed: {
    ...mapState(['cartItems']),
    selectedItemCount() {
      return this.cartItems.filter(item => this.selectedItems[item.id]).length;
    },
    selectedItemTotal() {
      return this.cartItems.reduce((total, item) => {
        if (this.selectedItems[item.id]) {
          return total + item.price * item.quantity;
        }
        return total;
      }, 0);
    },
    hasSelectedItems() {
      return this.cartItems.some(item => this.selectedItems[item.id]);
    }
  },
  data() {
    return {
      selectedItems: {}
    };
  },
  methods: {
    ...mapActions(['removeFromCart']),
    onCheckboxChange(productId, isChecked) {
      if (!isChecked) {
        this.selectedItems[productId] = false;
      } else {
        // 当勾选时，确保数量不为0
        const product = this.cartItems.find(p => p.id === productId);
        if (product && product.quantity > 0) {
          this.selectedItems[productId] = true;
        }
      }
    },
    placeOrder() {
      if (!this.hasSelectedItems) {
        this.$message.warning('请选择至少一个商品进行下单');
        return;
      }
      const orderItems = this.cartItems.filter(item => this.selectedItems[item.id]);
      const order = {
        id: Date.now().toString(),
        time: new Date().toISOString(),
        totalAmount: this.selectedItemTotal,
        items: orderItems.map(item => ({ ...item, quantity: item.quantity }))
      };
      this.$store.dispatch('addOrder', order);
      // 清空已选商品
      this.selectedItems = {};
      // 清空购物车
      this.cartItems.forEach(item => {
        if (this.selectedItems[item.id]) {
          this.removeFromCart({ id: item.id });
        }
      });
      this.$message.success('下单成功');
    },
    removeOne(productId) {
      const product = this.cartItems.find(p => p.id === productId);
      if (product && product.quantity > 1) {
        product.quantity -= 1;
        this.updateCartQuantity(product);
      } else if (product) {
        this.removeFromCart({ id: productId });
      }
    },
    removeAll(productId) {
      this.removeFromCart({ id: productId });
    },
    updateCartQuantity(product) {
      const index = this.cartItems.findIndex(p => p.id === product.id);
      if (index !== -1) {
        this.cartItems[index] = { ...product };
        localStorage.setItem('cartItems', JSON.stringify(this.cartItems));
      }
    }
  }
};
</script>

<style>
.wishlist {
  padding: 20px;
}
.checkout-bar {
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f3f3f3;
  text-align: right;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>